/**
 * Copyright (c) 2019 xstgongyi.org
 * All rights reserved.
 */
package org.xstgongyi.eduaid.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xstgongyi.eduaid.common.ControllerHelper;
import org.xstgongyi.eduaid.dataobject.SemesterDO;
import org.xstgongyi.eduaid.service.SchoolYearService;
import org.xstgongyi.eduaid.service.SemesterService;

/**
 * @author oldcrane<br/>
 * @created 2019-04-02
 */
@Controller
@RequestMapping("/semesters")
public class SemesterController {

	@Autowired
	private SchoolYearService schoolYearService;

	@Autowired
	private SemesterService semesterService;

	@GetMapping("/entry")
	public String entryPage(ModelMap map) {
		return "masterdata/semester";
	}

	@GetMapping("")
	@ResponseBody
	public Map<String, Object> list(@RequestParam(name = "active", required = false) Boolean active) {
		List<SemesterDO> semesterDOList = null;
		if (null == active) {
			semesterDOList = semesterService.listAll();
		} else {
			semesterDOList = semesterService.listByStatus(active);
		}

		List<SemesterVO> voList = new ArrayList<>();
		for (SemesterDO semesterDO : semesterDOList) {
			SemesterVO vo = SemesterVO.of(semesterDO);
			vo.addSchoolYearInfo(schoolYearService.getById(semesterDO.getSchoolYearId()));
			voList.add(vo);
		}
		return ControllerHelper.successResponse(voList);
	}

	@PostMapping("")
	@ResponseBody
	public Map<String, Object> add(@RequestBody SemesterVO vo) {
		if (null == vo) {
			return (ControllerHelper.errorResponse(1, "非法输入：要添加的学期参数为空对象。"));
		}
		semesterService.insert(vo.getName(), vo.getSchoolYearId(), vo.getActive());
		return ControllerHelper.successResponse(null);
	}

	@GetMapping("/{id}")
	@ResponseBody
	public Map<String, Object> get(@PathVariable("id") Integer id) {
		SemesterDO semester = semesterService.getById(id);
		if (null != semester) {
			return ControllerHelper.successResponse(semester);
		} else {
			return ControllerHelper.errorResponse(1, "Semester does not exist(id:" + id + ").");
		}
	}

	@PostMapping("/{id}")
	@ResponseBody
	public Map<String, Object> update(@PathVariable("id") Integer id, @RequestBody SemesterVO vo) {
		if (null == vo) {
			return (ControllerHelper.errorResponse(1, "非法输入：要修改的学期参数为空对象。"));
		}
		semesterService.update(id, vo.getName(), vo.getSchoolYearId(), vo.getActive());
		return ControllerHelper.successResponse(null);
	}

}
